/*
 * Copyright (c), 
 * All rights reserved.
 *
 * Change Logs:
 * Date         Author      Action
 * 2019/05/xx   zck         Create this file
 */


/**
 * @file 	drv_systick.c
 * @brief 	systick嘀嗒定时器
 * @details 
 * 
 */#include "stm32f4xx.h"

static uint8_t fs_us=0;
static uint16_t fs_ms=0;

void SYSTICK_Config(uint8_t sysClk)
{
	SysTick->CTRL &= ~0x05;

	// 168MHz/8=21MHz
	fs_us = sysClk / 8;
	fs_ms = (uint16_t)fs_us * 1000;
}

static void systickDelayMs(uint16_t ms)
{
	uint32_t temp;
	
	SysTick->LOAD = (uint32_t)ms * fs_ms;
	SysTick->VAL = 0x00;
	SysTick->CTRL |= 0x01;

	do
	{
		temp = SysTick->CTRL;
	} while ((temp&0x01) && (!(temp&(1<<16))));

	SysTick->CTRL &= ~0x01;
	SysTick->VAL = 0x00;
}

void SYSTICK_DelayNms(uint16_t ms)
{
	uint16_t quotient;
	uint16_t remainder;

	quotient = ms / 500;
	remainder = ms % 500;


	while(quotient)
	{
		systickDelayMs(500);
		quotient--;
	}
	if(remainder)
		systickDelayMs(remainder);
	
	
}

void SYSTICK_DelayNus(uint16_t us)
{
	uint32_t temp;
	
	SysTick->LOAD = us * fs_us;
	SysTick->VAL = 0;
	SysTick->CTRL |= 0x01;

	do {
		temp = SysTick->CTRL;
	}
	while ((temp&0x01) && (!(temp&(1<<16))));

	SysTick->CTRL &= ~0x01;
	SysTick->VAL = 0;
}

